package com.daijie.demo

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import org.jsoup.Jsoup
import java.net.URLEncoder
import java.util.concurrent.TimeUnit

class MainActivity : AppCompatActivity(), IDisposables by IDisposablesImpl() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val api = App.instance.retrofit.create(Api::class.java)
        val cookieCache = App.instance.cookieCache
        api.queryCookies()
            .from_io()
            .doOnNext {
                Log.d(TAG, "response: ${it}")
                Log.d(TAG, "cookies : ${cookieCache.joinToString(",", "[", "]")}")
            }
            .map { html ->
                val doc = Jsoup.parse(html)
                val tokenEle =
                    doc.getElementsByAttributeValue("name", "__RequestVerificationToken")?.first()
                tokenEle?.attr("value") ?: ""
            }
            .flatMap { token ->
                api.login("15wjcao@stu.edu.cn", "Pw150214", token)
            }
            .flatMap {
                api.getToken()
            }
            .doOnNext {
                Log.d(TAG, "token = ${it}")
            }
            .flatMap { token ->
                api.getSyllabus(
                    token.vid,
                    token.timestamp,
                    token.app,
                    token.nonce,
                    // 要先encode一次才能正确请求
                    URLEncoder.encode(token.token, "UTF-8")
                )
            }
            .to_ui()
            .subscribe({
                Log.d(TAG, "${it}")
            }, {
                Log.e(TAG, Log.getStackTraceString(it))
            }).let {
                add(it)
            }
    }

    override fun onDestroy() {
        unsubscribe()
        super.onDestroy()
    }

    companion object {
        const val TAG = "DemoApp"
    }
}
